package product;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;

import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Stock2 extends JFrame {
	HashMap<String, StockData> map=new HashMap<String,StockData>();
	private JPanel contentPane;
	private JScrollPane scrollPane;
	private JTable table;
	private String findText;
	private HashMap data;
	String fileName="noName";
	String folder="/Img/";
	DefaultTableModel model;
	int columnX;
	int rowY;
	String value;
	Stock stock;
	boolean eScan;
	private Vector<SaleData> v2;
	private HashMap sTotal;
	String beforeCompareDate = "0";
	private String compareTime;
	private JLabel img2;
	private JButton btnNewButton;
	private JButton button;
	
	String FilePath = "C:\\data.xls"; //파일경로 및 파일명
	String SheetName = "stock"; //시트이름
	int cnt; //엑셀저장버튼 누른수.
	private JButton btnSaveExcel;
	
	/**
	 * @wbp.parser.constructor
	 */
	public Stock2(String findText, HashMap<String, ProductData> join) {
		this.findText = findText;
		this.data = join;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//
		setBounds(0, 0, 450, 453);//
		contentPane = new JPanel();//
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);//
		contentPane.setLayout(null);
		contentPane.add(getScrollPane());
		contentPane.add(getImg2());
		contentPane.add(getBtnNewButton());
		contentPane.add(getButton());
		contentPane.add(getBtnSaveExcel(), BorderLayout.SOUTH);
		contentPane.add(getBtnSaveExcel());
	}

	public Stock2(Vector<SaleData> v2, HashMap sTotal, String now) {
		this.v2 = v2;
		this.sTotal = sTotal;
		this.compareTime = now;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//
		setBounds(0, 0, 450, 300);//
		contentPane = new JPanel();//
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));//
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);//
		contentPane.add(getScrollPane2(), BorderLayout.CENTER);
		contentPane.add(getBtnSaveExcel(), BorderLayout.SOUTH);
		compareAtoB();
	}
	


	public void save() {
		
		try {
			FileOutputStream fw = new FileOutputStream("StockList.dat");
//			FileOutputStream fw = new FileOutputStream("c:\\StockList.dat");

			ObjectOutputStream bw = new ObjectOutputStream(fw);

			bw.writeObject(map);
			//result.setText("파일이 저장되었습니다.");

			bw.close();
			fw.close();			
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
	public void logo() {
		try {
			JFileChooser fc = new JFileChooser();
			int yn = fc.showOpenDialog(this);
			if (yn == JFileChooser.APPROVE_OPTION) {
				File f = fc.getSelectedFile();
				fileName = f.getPath();
				// 불러들인 파일 이미지를 label에 바로 뿌려준다.
				img2.setIcon(new ImageIcon(fileName));
				img2.setText("");
			}
		} catch (Exception ex) {
			
		}
	}

	private void compareAtoB() {
		
		Exception discord = new Exception();
		int aTob=0;
		int bToa=0;
		Vector<String> discordD = new Vector<String>();
		
		try {
			HashMap forCompare = new HashMap();
			
			for (int i = 0; i < table.getRowCount(); i++) {
				ProductData sale = new ProductData((String)table.getValueAt(i, 0), // 제품명
						Integer.parseInt((String)table.getValueAt(i, 1)), null, // 수량, 날짜 
						(String)table.getValueAt(i, 4), 0); // 코드, 가격 but 전의 테이블에서 가격은 5번째에 있었음

					if (forCompare.get(sale.getCode())==null) forCompare.put((String) table.getValueAt(i, 4), sale); //기존에 입력되어 있지 않다면,
					else { // 기존에 입력되어 있다면 키에서 숫자를 불러내서 더한다
						ProductData calcSale = (ProductData) forCompare.get(sale.getCode());
						int saleNow = calcSale.getVolume() + sale.getVolume();
						sale = new ProductData(table.getValueAt(i, 0)+"", saleNow, null, table.getValueAt(i, 4)+"", 0); 
						forCompare.put(sale.getCode(), sale);
					}
			}
			
			findText = "";
			Stock2 tb = new Stock2(findText, forCompare);
			tb.setLocation(tb.getX()+tb.getWidth()*2, tb.getY()+tb.getHeight());
			tb.setVisible(true);
			
//			Set keysetA = data.keySet(); // 널 포인터 익셉션
			Set keysetA = sTotal.keySet(); // 널 포인터 익셉션
			Set keysetB = forCompare.keySet();
			Iterator a = keysetA.iterator();
			Iterator b = keysetB.iterator();
			aTob=0;
			bToa=0;
			
			while (a.hasNext()) {
				String key = (String) a.next();
				ProductData aValue = (ProductData) sTotal.get(key);
				ProductData bValue = (ProductData) forCompare.get(key);
/*				System.out.println(sTotal.get(key) + "토탈");
				System.out.println(forCompare.get(key) + "비교");
				System.out.println(aValue.getVolume() + "토탈");
				System.out.println(bValue.getVolume() + "비교");*/
				if (keysetB.contains(key)) {
					aTob++;
				}
			}
			
			System.out.println(aTob);
			
			while (b.hasNext()) {
				String key = (String) b.next();
				if (keysetA.contains(key)) {
					bToa++;
				}
			}

			System.out.println(bToa);
			
			aTob=10;
			bToa=10;
			
			System.out.println(aTob);
			
			if (aTob != bToa || aTob == 0) { // a와 b의 코드 숫자가 일치하지 않거나, 일치하는 코드가 전혀 없는 경우
				throw discord;
			}
			else { // 제품 코드의 숫자가 일치하는 경우 제품의 개수도 일치하는 지 확인
				System.out.println("여기 오니?");
				Iterator d = keysetB.iterator();
				while (d.hasNext()) {
					String key = (String) d.next();
					ProductData aValue = (ProductData) sTotal.get(key);
					ProductData bValue = (ProductData) forCompare.get(key);
					if (aValue.getVolume()==aValue.getVolume()) {}
					else discordD.add(key);
				}
				if (discordD.size() != 0) throw discord;
			}
			
			JOptionPane.showMessageDialog(null, "모두 일치합니다");
			
		} catch (Exception e) {
/*			if (aTob != bToa) {
				if (Math.min(aTob, bToa)==aTob) JOptionPane.showMessageDialog(null, "제품이 누락되었습니다");
			}
			else if (aTob==0 && bToa==0) JOptionPane.showMessageDialog(null, "자료가 하나도 일치하지 않습니다");
			else {
				String discordDName = null;
				for (String str : discordD) {
					discordDName += " " + str;					
				}
				JOptionPane.showMessageDialog(null, discordDName + "의 개수가 맞지 않습니다");
			}*/
		}
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(5, 5, 424, 272);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}

	private JTable getTable() {
		if (table == null) {
			model = new DefaultTableModel(
			){	public boolean isCellEditable(int r, int c){ // 테이블 편집가능하게 한다. 
				  return false ;
			 }};
			 	model.addColumn("제품명");
				model.addColumn("수량");
				model.addColumn("날짜"); // if 생산즉시 입력된다면, 날짜를 하나만 넣어도 됨
				model.addColumn("제품코드");
				
				Set keyset = data.keySet();
				Iterator i = keyset.iterator();

					while(i.hasNext()) {
						String key = (String) i.next();
						ProductData val = (ProductData) data.get(key);

						if (findText.equals("") || findText.equals("LOAD")) {
							String[] temp = {val.getName(), ""+val.getVolume(), val.getNal(), val.getCode()};		
							StockData sd=new StockData(val.getCode(),val.getName(),val.getPrice(),val.getVolume());
							map.put(sd.getProCode(),sd);
							model.addRow(temp);
							if (findText.equals("LOAD")) setTitle("현재 재고");
							else setTitle("재고측 판매 집계");
						}
						
						else if (val.getName().equals(findText) || val.getCode().equals(findText) || val.getNal().equals(findText)) {
							String[] temp = {val.getName(), ""+val.getVolume(), val.getNal(), val.getCode()};							
							model.addRow(temp);			
							setTitle("\"" + findText + "\" 상세검색");
						}
					}
					
					if (findText.equals("LOAD"))	save();
				
				table = new JTable(model);
				table.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent e) {
						img2.setVisible(true);
						button.setVisible(true);
						btnNewButton.setVisible(true);
						img2.setIcon(new ImageIcon("C:\\Img\\"+findText+".png"));
					}
				});
			/*table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					columnX = table.getSelectedColumn();
					rowY = table.getSelectedRow();
					System.out.println(stock.findText);
					stock.findText = (String) table.getValueAt(rowY, columnX);
					System.out.println(stock.findText);
					stock.scan();
				}
			});*/
			table.setAutoCreateRowSorter(true);
			TableRowSorter tableSorter = new TableRowSorter(table.getModel());
			table.setRowSorter(tableSorter);
			table.getRowSorter().toggleSortOrder(0);
		}
		return table;
	}
	
	private JScrollPane getScrollPane2() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable2());
		}
		return scrollPane;
	}

	private JTable getTable2() {
		if (table == null) {
			model = new DefaultTableModel(
			){	public boolean isCellEditable(int r, int c){ // 테이블 편집가능하게 한다. 
				  return false ;
			 }};
			 	model.addColumn("제품명");
				model.addColumn("수량");
				model.addColumn("생산일"); // if 생산즉시 입력된다면, 날짜를 하나만 넣어도 됨
				model.addColumn("판매일");
				model.addColumn("제품코드");
				
				for (SaleData s : v2) { // 반복문
//					Collection c = sTotal.values();
//					System.out.println(c); //외계어
					Set keys = sTotal.keySet();
//					System.out.println(keys);
//					System.out.println(s.getProCode());
//					System.out.println(keys.contains(s.getProCode())); // 대소문자 문제있음 판매조 대소문자 구분 제대로 안하지!-_-!
//					if (keys.contains(s.getProCode())) {
//					if (keys.containsIgnorecase(s.getProCode())) { //안됨
					if (keys.contains("A001")) {
						String reDate = s.getSaleDate();
						String[] splitWord = {"년", "월", "일"/*, "시", "분", "초"*/};
						int dDate;
						if (s.getSaleDate().contains("월")) { //만약에 같은 문자가 있다면
							String[] splitAfter;
							for (int i = 0; i < splitWord.length; i++) { // 리스트 검색
								System.out.println(reDate);
								splitAfter = reDate.split(splitWord[i], reDate.length());
								for (int j = 0; j < splitAfter.length; j++) {
									if (j==0)	reDate = splitAfter[j].trim();
									else reDate += splitAfter[j].trim();
								}
							}
						}
						else if ((s.getSaleDate().contains("-"))) {
							splitWord = s.getSaleDate().split("-", s.getSaleDate().length());
							for (int i = 0; i < splitWord.length; i++) {
								if (i==0)	reDate = splitWord[i].trim();
								else reDate += splitWord[i].trim();
							}
						}
						else if (s.getSaleDate().contains(" ")){
							splitWord = s.getSaleDate().split("\\s", s.getSaleDate().length());
							for (int i = 0; i < splitWord.length; i++) {
								if (i==0)	reDate = splitWord[i];
								else reDate += splitWord[i];
							}
						}
						else reDate = s.getSaleDate(); 
						
						if (reDate.startsWith("20")) {
							dDate = Integer.parseInt(reDate.substring(2, 8));
						}
						else dDate = Integer.parseInt(reDate.substring(0, 6));
						
						if (dDate > Integer.parseInt(beforeCompareDate) && dDate<= Integer.parseInt(compareTime)) {
							String[] temp = {s.getProName(), "-"+s.getSaleEa(), null, s.getSaleDate(), s.getProCode()}; 
							model.addRow(temp);							
						}
					}
				}
				
				setTitle("재고 측 판매 내역");
			
				table = new JTable(model);

			table.setAutoCreateRowSorter(true);
			TableRowSorter tableSorter = new TableRowSorter(table.getModel());
			table.setRowSorter(tableSorter);
			table.getRowSorter().toggleSortOrder(0);
		}
		return table;
	}
	
/*	void scan() { // 자기자신을 부르는 것도 가능함
		Stock2 tb = new Stock2(data, jemok); // 그냥 Re의 생성자에 검색 메소드를 때려박자
		tb.setVisible(true);
	}*/
	private JLabel getImg2() {
		if (img2 == null) {
			img2 = new JLabel("");
			img2.setVisible(false);
			img2.setBounds(5, 287, 238, 118);
		}
		return img2;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("사진추가");
			btnNewButton.setVisible(false);
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					logo();			
					StockData sd=new StockData(fileName);
					map.put(sd.getProCode(),sd);
				}
			});
			btnNewButton.setBounds(288, 327, 97, 23);
		}
		return btnNewButton;
	}
	private JButton getButton() {
		if (button == null) {
			button = new JButton("사진저장");
			button.setVisible(false);
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						File f1 = new File(folder);
						if(!f1.exists()){
							f1.mkdirs();
						}
						
						BufferedImage img = ImageIO.read(new File(fileName));
						ImageIO.write(img, "png", new File(folder + findText + ".png"));
							
					}catch(Exception ex){
						
					}
				}
			});
			button.setBounds(288, 360, 97, 23);
		}
		return button;
	}

	private JButton getBtnSaveExcel() {
		if (btnSaveExcel == null) {
			btnSaveExcel = new JButton("엑셀로 저장");
			btnSaveExcel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					saveExcel();					
					
					JOptionPane.showMessageDialog(null, FilePath + " 에 파일이 저장되었습니다.");
				}
			});
			btnSaveExcel.setBounds(288, 294, 97, 23);
		}
		return btnSaveExcel;
	}
	
	public void saveExcel(){
		String[] getColumn = new String[table.getColumnCount()];
		for(int i=0; i<table.getColumnCount(); i++){ //컬럼명 받기
			getColumn[i] = table.getColumnName(i);
		}
		
		String[][] getData = new String[table.getRowCount()][table.getColumnCount()]; //데이터받기
		for(int i=0; i<table.getRowCount(); i++){
			for(int j=0; j<table.getColumnCount(); j++){
				getData[i][j] = (String)table.getValueAt(i,j);
			}
		}
		
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(new File(FilePath)); //파일경로설정
			WritableSheet sheet = workbook.createSheet(SheetName, 0); // 시트이름과 시트번호
			
			jxl.write.WritableCellFormat columnFormat = new WritableCellFormat(); //컬럼포맷 스트링.
			jxl.write.WritableCellFormat dataFormat  = new WritableCellFormat(); //데이터포맷 스트링.
			 
			columnFormat.setBackground(jxl.format.Colour.ORANGE); //컬럼포맷 백그라운드 색상설정.
			
			
			
			for(int i=0; i<getColumn.length; i++){ //컬럼명 넣어주기.
				jxl.write.Label label = new jxl.write.Label(i, 0, getColumn[i], columnFormat); //(열,행,컬럼명,스트링포맷)
				 sheet.addCell(label);
			}
			
			for(int i=0; i<getData.length; i++){
				for(int j=0; j<getData[i].length; j++){
					jxl.write.Label lbl = new jxl.write.Label(j, i+1, getData[i][j], dataFormat); //(열,행,데이터,스트링포맷)
					sheet.addCell(lbl);
				}
			}
			
			workbook.write();
			workbook.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}